import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('../views/LayoutView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/HomeView.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'user',
          name: 'user',
          component: () => import('../views/UserView.vue'),
          meta: { title: '用户管理' }
        },
        {
          path: 'equipment',
          name: 'equipment',
          component: () => import('../views/EquipmentView.vue'),
          meta: { title: '设备管理' }
        },
        {
          path: 'command',
          name: 'command',
          component: () => import('../views/CommandView.vue'),
          meta: { title: '命令管理' }
        },
        {
          path: 'company',
          name: 'company',
          component: () => import('../views/CompanyView.vue'),
          meta: { title: '公司管理' }
        },
        {
          path: 'agreement',
          name: 'agreement',
          component: () => import('../views/AgreementView.vue'),
          meta: {
            title: '协议管理',
            requiresAuth: true
          }
        },
        {
          path: 'settings',
          name: 'settings',
          component: () => import('../views/SettingsView.vue'),
          meta: { title: '个人设置' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
